package com.cap6402.project.two;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class GameFinishedActivity extends Activity implements OnClickListener {
	TextView scored, score;
	CustomButton playAgain, mainMenu,postScore;
	Integer newScore;
	String levelId;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.gamefinished);
		scored = (TextView) GameFinishedActivity.this.findViewById(R.id.scored);
		score = (TextView) GameFinishedActivity.this.findViewById(R.id.score);
		playAgain = (CustomButton) GameFinishedActivity.this.findViewById(R.id.playagainButton);
		mainMenu = (CustomButton) GameFinishedActivity.this.findViewById(R.id.mainButton);
		postScore = (CustomButton) GameFinishedActivity.this.findViewById(R.id.postscoreButton);
		playAgain.setOnClickListener(this);
		mainMenu.setOnClickListener(this);
		postScore.setOnClickListener(this);
		
		Typeface tf = Typeface.createFromAsset(getAssets(),
                "font/Ribbon.otf");
		
		scored.setTypeface(tf);
		score.setTypeface(tf);
		Bundle extras = getIntent().getExtras(); 
		score.setText(extras.getString("score") + " Points");
		
		levelId = extras.getString("level");
		Integer oldScore = 0;
		if(Utility.levelScores.get(levelId) != null) {
			if(Utility.levelScores.get(levelId).get(Utility.userID) != null)
				oldScore = Utility.levelScores.get(levelId).get(Utility.userID);
		} else {
			Utility.levelScores.put(levelId,new LinkedHashMap<String,Integer>());
		}

		NumberFormat format = NumberFormat.getInstance(Locale.US);
		try {
			newScore = format.parse(extras.getString("score")).intValue();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(newScore <= oldScore)
			postScore.setEnabled(false);
		
		
	}
	@Override
	public void onClick(View view) {
		CustomButton btn = (CustomButton) view;
		if(btn.equals(playAgain)) {
			Intent intent = new Intent(this, SocialNetworkActivity.class);
			intent.putExtra("user", levelId);
			startActivity(intent);
		} else if(btn.equals(mainMenu)) {
			Intent intent = new Intent(this, MainMenuActivity.class);
			startActivity(intent);
		} else if(btn.equals(postScore)) {
			//post new score
			Utility.levelScores.get(levelId).put(Utility.userID, newScore);
			new PostScoreAsyncTask().execute();
		}
	}
	
	private class PostScoreAsyncTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			InputStream is = null;
			StringBuilder sb;
			String result = "";
			try{
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://cise.ufl.edu/~acordar/socialnetwork/postscore.php");
			    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			    nameValuePairs.add(new BasicNameValuePair("score", newScore.toString()));
			    nameValuePairs.add(new BasicNameValuePair("user", Utility.userID));
			    nameValuePairs.add(new BasicNameValuePair("level",levelId));
			    nameValuePairs.add(new BasicNameValuePair("name",Utility.name));
			   // System.out.println(Utility.userID + " " + levelId + " " + Utility.name);
			    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			}catch(Exception e){
				Log.e("log_tag", "Error in http connection"+e.toString());
			}
			try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "");
				result = sb.toString();	
			}catch(Exception e){
				Log.e("log_tag", "Error converting result "+e.toString());
			}
			
			return result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			//System.out.println(result);
			postScore.setEnabled(false);
		}
		
	}
}
